from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from database.database import get_db
from core.base.api_mode import ApiResponse, api_success
from core.token_manager import get_current_user
from modules.system.params.menu_params import MenuQuery
from modules.system.schemas.menu_schemas import MenuCreate, MenuUpdate
from modules.system.services.menu_service import MenuService
from modules.system.services.user_service import UserService
from modules.system.vos.menu_vo import MenuResponse, MenuListResponse, MenuTreeResponse, MenuTreeNode, RouteMeta
from core.pagination import DependsPagination, PageData

router = APIRouter()


@router.post("/create", response_model=ApiResponse[MenuResponse])
async def create_menu(payload: MenuCreate, db: AsyncSession = Depends(get_db)):
    menu = await MenuService.create_menu(db, payload)
    return api_success(MenuResponse.model_validate(menu), msg="创建成功")


@router.post("/list", 
    response_model=ApiResponse[PageData[MenuResponse]],
    summary="获取菜单列表",
    dependencies=[DependsPagination],
)
async def list_menus(query: MenuQuery, db: AsyncSession = Depends(get_db)):
    result = await MenuService.get_menus_with_pagination(db, query)
    return api_success(data=result, msg="获取成功", )

@router.get("/tree", response_model=ApiResponse[MenuTreeResponse])
async def get_menu_tree(
    type: int | None = None,
    status: bool | None = None,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_current_user),
):
    # 优先使用数据库中的用户角色ID列表
    role_values = current_user.get("roles", []) if isinstance(current_user, dict) else []
    uid = current_user.get("uid") if isinstance(current_user, dict) else None
    if uid is not None:
        profile = await UserService.get_user_profile_by_id(db, uid)
        if profile and profile.get("roles") is not None:
            role_values = profile["roles"]

    items = await MenuService.get_tree(db, type=type, status=status, role_ids=role_values)
    nodes = [MenuTreeNode.model_validate(i) for i in items]
    return api_success(MenuTreeResponse(items=nodes), msg="获取成功")


@router.get("/tree/all", response_model=ApiResponse[MenuTreeResponse])
async def get_menu_tree_all(
    type: int | None = None,
    status: bool | None = None,
    db: AsyncSession = Depends(get_db)
):
    items = await MenuService.get_tree(db, type=type, status=status, role_ids=None)
    nodes = [MenuTreeNode.model_validate(i) for i in items]
    return api_success(MenuTreeResponse(items=nodes), msg="获取成功")

@router.put("/{permission_id}", response_model=ApiResponse[MenuResponse])
async def update_menu(permission_id: int, payload: MenuUpdate, db: AsyncSession = Depends(get_db)):
    menu = await MenuService.update_menu(db, permission_id, payload)
    return api_success(MenuResponse.model_validate(menu), msg="更新成功")


@router.delete("/{permission_id}", response_model=ApiResponse[dict])
async def delete_menu(permission_id: int, db: AsyncSession = Depends(get_db)):
    await MenuService.delete_menu(db, permission_id)
    return api_success({"message": f"权限ID {permission_id} 删除成功"}, msg="删除成功")